package com.hmdp.utils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorder {

    private static final long BEGIN_TIMESTAMP = 1640995200L;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // 使用构造函数注入

    /**
     * 64位：一个符号位  32个时间戳   31个序列号
     *
     * @return
     */
    public long netxId(String keyprefix) {
//        生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowTime = now.toEpochSecond(ZoneOffset.of("+8"));
        long timecurrent = nowTime - BEGIN_TIMESTAMP;

//        序列号
        String yyyyMMdd = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//        自增长
//        不同的key都是重新开始的。每一天都是新的key，所以不会塞满32位。
        long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyprefix + ":" + yyyyMMdd);
//
        return timecurrent << 32 | increment;
    }

    public static void main(String[] args) {
//        2022-01-01T00:00
        LocalDateTime of = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
        System.out.println(of);
        long l = of.toEpochSecond(ZoneOffset.of("+8"));
        System.out.println(LocalDateTime.now());
    }
}
